import Vue from "vue";
import Vuex from "vuex";

import dynamicRoutes from "../router/dynamicRoutes";

import allRoutes from "../router/allRoutes";

import recursionRoutes from "../utils/recursionRoutes";

import * as api from "@/api";

import router from "../router";

Vue.use(Vuex);

//刷新页面vuex会丢失因为 刷新页面会重新执行vuex的逻辑,也就意味着,vuex重新被初始化了,而我们的用户信息在登入的时候才存到vuex中的,所以我们需要额外的操作 防止用户信息丢失

//额外操作就是将用户信息保存到localstorage中

//问题1:如何进行调试
//问题2:数据如何进行验证,是否符合预期

let userInfo = localStorage.getItem("qf-userInfo") || "{}";
let buttons = localStorage.getItem("permissionButtons") || "[]";
console.log(buttons);
export default new Vuex.Store({
  state: {
    userInfo: JSON.parse(userInfo),
    sideMenu: [], //用户侧边栏菜单
    menuCollapse: false, //控制侧边菜单的收起和展开
    breadCrumb: [], //面包屑数据
    userButtons: JSON.parse(buttons), //用户按钮
  },
  mutations: {
    //更改state的唯一方式
    SET_USERINFO(state, payload) {
      state.userInfo = payload;
    },
    //设置菜单收起和展开
    SET_MENU_COLLAPSE(state) {
      state.menuCollapse = !state.menuCollapse;
    },
    //设置菜单
    SET_SIDE_MENU(state, payload) {
      state.sideMenu = [...payload];
      //设置dynamicRoutes=>讲用户路由添加到当前数组中的path="/"的对象的children属性中
      //添加完成之后,还需要将整个dynamicRoutes通过addRoutes的方式添加到系统路由routes中

      let target = dynamicRoutes.find((item) => item.path === "/");
      target.children = [...payload];
      //将dynamicRoutes动态添加到路由中
      // console.log(dynamicRoutes)
      router.addRoutes(dynamicRoutes);
    },
    //设置面包屑
    SET_BREADCRUMB(state, payload) {
      state.breadCrumb = payload;
    },
    //设置用户的按钮权限
    SET_USER_BUTTONS(state, payload) {
      state.userButtons = payload;
    },
  },
  getters: {
    avatarUrl(state) {
      return state.userInfo.headimgurl
        ? state.userInfo.headimgurl
        : "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";
    },
  },
  actions: {
    //发起异步请求,然后获取用户菜单
    FETCH_MENU_LIST({ commit }) {
      //发请求获取用户菜单
      return api.getMenuListApi().then((res) => {
        // console.log(res)
        let menuList = res.data.menuList;
        //递归,匹配出用户路由
        let userMenu = recursionRoutes(allRoutes, menuList);
        commit("SET_SIDE_MENU", userMenu);
      });
    },
  },
  modules: {},
});
